﻿using GalaSoft.MvvmLight.Command;
using JiveMessenger.Models;
using JiveMessenger.Utilities;
using JiveMessenger.ViewModels;
using JmShared;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using Windows.UI;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;

namespace JiveMessenger.SampleData
{
    class SampleViewModelContactList : IViewModelContactList
    {
        public RelayCommand OpenAddContactPageCommand { get; set; }
        public RelayCommand OpenGroupAndContactPageCommand { get; set; }
        public RelayCommand CreateGroupCommand { get; set; }
        public RelayCommand<IChatGroup> InviteContactToGroupCommand { get; set; }
        public RelayCommand<IChatGroup> LeaveGroupCommand { get; set; }
        public RelayCommand<IChatGroup> BlockGroupCommand { get; set; }
        public RelayCommand<IContact> OpenPmCommand { get; set; }
        public RelayCommand OpenNotificationsCommand { get; set; }
        public RelayCommand<IContact> IgnoreContactCommand { get; set; }
        public RelayCommand<IChatGroup> OpenGroupCommand { get; set; }
        public RelayCommand<IChatGroup> ManageGroupCommand { get; set; }
        public RelayCommand<IContact> AddCustomEmoticonsCommand { get; set; }
       public RelayCommand<IEmoticon> DeleteEmoticonCommand { get; set; }
       public RelayCommand AddEmoticonCommand { get; set; }
        public SampleViewModelContactList()
        {
            RunOnNetworkConnect();
        }

        public void Cleanup()
        {

        }

        private ObservableCollection<IContact> _contacts;
        public ObservableCollection<IContact> Contacts
        {
            get
            {
                if (_contacts == null)
                {
                    System.Collections.ObjectModel.ObservableCollection<IContact> samples = new System.Collections.ObjectModel.ObservableCollection<IContact>();
                    Random rand = new Random((int)DateTime.Now.Ticks);
                    string[] usernames = new string[] { "ole.skodje@gmail.com", "foo@bar.com", "testuser@testdomain.com", "trololo@tralala.com", "larsolav@gmail.com", "heihei@test.com", "lorem@ipsum.com" };
                    string[] ids = new string[] { "#pc1234", "#wp1234", "#pc2345", "#wp2345", "#pc3456", "#pc54555", "#android1234", "#android2345", "#android3456" };
                    string[] nicknames = new string[] { "long,long,long nick", "long,long,long,long,long,longlong,long,long nick", "this is a very long nick", "sverre", "ole", "lars", "stian", "this is an even longer nick then before" };
                    SolidColorBrush[] colors = new SolidColorBrush[] { new SolidColorBrush(Colors.Red), new SolidColorBrush(Colors.Black), new SolidColorBrush(Colors.Blue),
                        new SolidColorBrush(Colors.Yellow), new SolidColorBrush(Colors.Violet), new SolidColorBrush(Colors.Fuchsia) };
                    Dictionary<int, string> chatGroups = new Dictionary<int, string>();
                    for (int i = 0; i < rand.Next(3, 6); i++)
                    {
                        chatGroups.Add(i, string.Format("Group {0}", i));
                    }

                    int clientNum = rand.Next(4, 6);
                    for (int i = 0; i < clientNum; i++)
                    {
                        string username = usernames[rand.Next(0, usernames.Length)];
                        string userID = username + ids[rand.Next(0, ids.Length)];
                        JmShared.ClientStatus clientStatus = JmShared.ClientStatus.Available;
                        JmShared.DeviceType deviceType = JmShared.DeviceType.PC;
                        int status = rand.Next(1, 5);
                        if (status == 1)
                        {
                            clientStatus = JmShared.ClientStatus.Afk;
                            deviceType = JmShared.DeviceType.PC;
                        }
                        else if (status == 2)
                        {
                            clientStatus = JmShared.ClientStatus.Available;
                            deviceType = JmShared.DeviceType.Android;
                        }
                        else if (status == 3)
                        {
                            clientStatus = JmShared.ClientStatus.Busy;
                            deviceType = JmShared.DeviceType.WindowsPhone;
                        }
                        else if (status == 4)
                            clientStatus = JmShared.ClientStatus.Offline;
                        List<IChatGroup> userGroups = new List<IChatGroup>();

                        int max = rand.Next(1, 3);
                        for (int n = 0; n < max; n++)
                        {
                            var value = chatGroups.ElementAt(rand.Next(0, chatGroups.Count));
                            Dictionary<string, GroupPrivilege> groupMembers = new Dictionary<string, GroupPrivilege>();
                            groupMembers.Add(username, GroupPrivilege.Owner);
                            for (int r = 0; r < max; r++)
                            {
                                string user = usernames[rand.Next(0, usernames.Length)];
                                if (!groupMembers.ContainsKey(user))
                                    groupMembers.Add(user, GroupPrivilege.Member);
                            }

                            if (!userGroups.Any(x => x.ID == value.Key.ToString()))
                                userGroups.Add(new JiveChatGroupModel(value.Key.ToString(), value.Value, groupMembers) { IsBlocked = rand.Next(1, 100) > 50 ? true : false });
                        }

                        samples.Add(new Models.JiveContactModel("1", userID, nicknames[rand.Next(0, nicknames.Length)] + " (" + i + ")", DeviceType.PC)
                        {
                            AfkStart = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, rand.Next(0, 4), rand.Next(0, 60), rand.Next(0, 60)),
                            UnreadMessageCount = rand.Next(0, 20),
                            ClientStatus = clientStatus,
                            ChatGroups = new ObservableCollection<IChatGroup>(userGroups),
                            DeviceType = deviceType,
                            IsIgnored = rand.Next(0, 100) >= 50,
                            FontColor = colors[rand.Next(0, 6)].Color,
                            ShowInContactList=true,
                            Avatar = "ms-appx:///Assets/Images/avatar_empty_50x50.png" //new BitmapImage(new Uri("ms-appx:///Assets/Images/avatar_empty.png"))

                        });

                    }

                    _contacts = new ObservableCollection<IContact>(samples.OrderBy(x =>
                        {
                            if (x.ClientStatus == JmShared.ClientStatus.Offline)
                                return 1;
                            else
                                return 0;
                        }));
                   // this.CurrentUser = _contacts[0];

                   //GroupedContacts = from c in _contacts group c by c.NickName into grp orderby grp.Key select grp;

                    //foreach (IChatGroup grp in this.CurrentUser.ChatGroups)
                    //{
                    //    VisualGroup vGrp = new VisualGroup(grp);
                    //    vGrp.Contacts = new ObservableCollection<IContact>(_contacts.Where(x =>x.ChatGroups.Contains(grp)));
                    //    GroupedContacts.Add(vGrp);
                    //}
                }

                return _contacts;
            }
            set
            {

            }
        }

        public void SetContactAsOffline(string userName)
        {
            throw new NotImplementedException();
        }


        public void RunOnNetworkConnect()
        {
            Contacts = new ObservableCollection<IContact>();
        }


        public IContact CurrentUser
        {
            get
            {
                return Contacts.FirstOrDefault();
            }
            set
            {
              
            }
        }




        public void RunOnNetworkDisconnect()
        {

        }


        public ClientStatus ManualClientStatus
        {
            get
            {
                return ClientStatus.Afk;
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        private ObservableCollection<VisualGroup> _groupedContacts;
        public ObservableCollection<VisualGroup> GroupedContacts
        {
            get
            {
                if (_groupedContacts == null)
                {
                    if (Contacts != null)
                    {
                        _groupedContacts = CreateVisualGroups();// new ObservableCollection<VisualGroup>();
                        //foreach (IChatGroup grp in this.CurrentUser.ChatGroups)
                        //{
                        //    VisualGroup vGrp = new VisualGroup(grp);
                        //   // vGrp.Contacts = new ObservableCollection<IContact>(_contacts.Where(x => x.ChatGroups.Contains(grp)));
                        //    _groupedContacts.Add(vGrp);
                        //}
                        
                    }
                }
                return _groupedContacts;
            }
            set
            {
            }
        }

        private ObservableCollection<VisualGroup> CreateVisualGroups()
        {
            var groupedContacts = new ObservableCollection<VisualGroup>();
            if (this.CurrentUser == null)
                return groupedContacts;
            VisualGroup friendsGroup = new VisualGroup(new JiveFriendsGroupModel("JiveFriendsGroup", "All Contacts"));
            var friendContacts = new ObservableCollection<IContact>(Contacts.Where(x => x.ShowInContactList && !x.Equals(CurrentUser)));
            SortContactsByNameAndStatus(friendContacts);
            friendsGroup.Contacts = friendContacts;

            groupedContacts.Add(friendsGroup);
            foreach (IChatGroup grp in this.CurrentUser.ChatGroups)
            {
                VisualGroup vGrp = new VisualGroup(grp);
                var grpContacts = new ObservableCollection<IContact>(Contacts.Where(x => x.ShowInContactList && !x.Equals(CurrentUser)));
                SortContactsByNameAndStatus(grpContacts);
                vGrp.Contacts = grpContacts;
                groupedContacts.Add(vGrp);
            }
            return groupedContacts;
        }
        private void SortContactsByNameAndStatus(ObservableCollection<IContact> contacts)
        {
            List<IContact> sorted = contacts.OrderBy(x =>
            {
                if (x.ClientStatus == ClientStatus.Offline)
                    return true;
                else
                    return false;
            })
                .ThenBy(x => x.PrettyName).ToList();

            int index = 0;
            while (index < sorted.Count)
            {
                if (!contacts[index].Equals(sorted[index]))
                {
                    IContact t = contacts[index];
                    contacts.Move(index, sorted.IndexOf(t));
                    //contacts.RemoveAt(index);
                    // contacts.Insert(sorted.IndexOf(t), t);
                }
                else
                {
                    index++;
                }
            }
        }

        public void AddOrUpdateContact(UserInfo user, bool createVisualGroups)
        {
            throw new NotImplementedException();
        }
    }
}
